//
// Created by bxw57 on 2024/6/12.
//

#include <stdexcept>
#include "MyArray.h"

template<class T>
MyArray<T>::MyArray(const MyArray &tmp) {
    arr = new T[tmp.cap];
    cap = tmp.cap;
    top = tmp.top;
    for (int i = 0; i < top; i++)
        arr[i] = tmp.arr[i];
}

template<class T>
void MyArray<T>::operator=(const MyArray &tmp) {
    cap = tmp.cap;
    top = tmp.top;
    if (arr != NULL)
        delete[] arr;
    arr = new T[cap];
    for (int i = 0; i < top; i++)
        arr[i] = tmp.arr[i];
}

template<class T>
void MyArray<T>::push_back(T val) {
    if (top == cap) {
        //扩容
        T tmp[cap];
        for (int i = 0; i < cap; i++)
            tmp[i] = arr[i];
        cap *= 2;
        delete[] arr;
        arr = new T[cap];
        for (int i = 0; i < cap; i++)
            arr[i] = tmp[i];
    }
    arr[top++] = val;
}

template<class T>
T MyArray<T>::pop() {
    if (top == 0)
        throw std::runtime_error("Stack is empty");
    return arr[--top];
}


template<class T>
int MyArray<T>::getNum() {
    return top;
}

template<class T>
int MyArray<T>::getCap() {
    return cap;
}

template<class T>
T MyArray<T>::indexOf(int idx) {
    if (idx < 0 || idx >= top)
        throw std::runtime_error("index is out of range");
    return arr[idx];
}

template<class T>
void MyArray<T>::show() {
    for (int i = 0; i < top; i++)
        std::cout << arr[i] << " ";
    std::cout << std::endl;
}